﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;
using Ecopsy.DataTier;
using Ecopsy.Tools;
using SqlLibrary;

public partial class iSales : iSales_Page 
{

    public string   KeyPref =       "Ctl_ctlSurfaceList";
    private string  sContractID=    "ee370ee8-16be-4e69-96dd-0b6b90890342";

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            DtStart =Ecopsy.Tools.DateTimeTools.GetFisrtDayInMonth (DateTime.Now);
            DtEnd =Ecopsy.Tools.DateTimeTools.GetFisrtDayInMonth (DateTime.Now).AddMonths (3);
            DetailsPeriod =DateTimeTools.TimePeriod .Month ;
            InitControls();
            ctlFilterBar1_OnFindClik("");
        }
        else 
            InitControls();
    }

    #region Список

    // сторон и конторла управление размером периода
    public void InitControls()
    {
        ctlFilterBar1.OnFindClik = ctlFilterBar1_OnFindClik;
        ctlFilterBar1.OnFilterListClik = ctlFilterBar1_OnFilterListClik;
        ctlFilterBar1.OnFilterSaveClik = ctlFilterBar1_OnFilterSaveClik;
        ctlFilterBar1.HintServiceMethod = "GetTaskListParams";
                
        cmbPeriodType.Attributes .Add ("onchange", "OnPeriodChange()");
        txtDtStart.Attributes.Add("onchange", "OnPeriodChange()");
        txtDtEnd.Attributes.Add("onchange", "OnPeriodChange()");
        string [] l= new string []{cmbPeriodType.ClientID ,txtDtStart.ClientID ,txtDtEnd.ClientID,ContractId };
        string script=string .Format ( " var PeriodType_ID='{0}';  var DtStart_ID='{1}'; var DtEnd_ID='{2}';  var ContractID ='{3}'",l);

        ScriptManager.RegisterClientScriptBlock(this, GetType(), Guid.NewGuid().ToString(), script, true); 
    }

    protected override void OnDataBinding(EventArgs e)
    {
        MyDataBind();
    }

    private bool ctlFilterBar1_OnFilterSaveClik()
    {
        //ModalPopupext_FilterSave.Show();
        return true;
    }



    private bool ctlFilterBar1_OnFilterListClik()
    {
        // ctlFilterList1.MyDataBind();
        // ModalPopupext_FilterList.Show();
        return true;
    }

    protected SideListWithContracts.SqlLoadStatment.Q_Type[] Q_TypeSet
    {
        get
        {
            List<SideListWithContracts.SqlLoadStatment.Q_Type> res = new List<SideListWithContracts.SqlLoadStatment.Q_Type>();
            if (chOnlyFree.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OnlyFree);
            if (chOnlyFull.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OnlyFull);
            if (chOverFlow_Q.Checked)
                res.Add(SideListWithContracts.SqlLoadStatment.Q_Type.OverFlow_Q);

            return res.ToArray<SideListWithContracts.SqlLoadStatment.Q_Type>();

        }

    }

    Func<string, DateTime> GetDate = delegate(string val)
    {
        DateTime s;
        if (DateTime.TryParse(val, out s))
            return s;
        else
            return DateTime.Now;

    };
    protected  DateTime DtStart 
    { 
        get {return GetDate(txtDtStart.Text);}
        set
        {
            txtDtStart.Text = value.ToShortDateString();
        }
    }

    protected DateTime DtEnd
    {
        get { return GetDate(txtDtEnd.Text); }
        set
        {
            txtDtEnd.Text = value.ToShortDateString ();
        }
    }

    protected Ecopsy.Tools.DateTimeTools.TimePeriod DetailsPeriod
    {
        get
    {
        switch (cmbPeriodType.SelectedValue)
        {
            case "1":
                return DateTimeTools.TimePeriod.Day;
            case "2":
                return DateTimeTools.TimePeriod.Week  ;
            case "3":
                return DateTimeTools.TimePeriod.Month  ;
        }
        return DateTimeTools.TimePeriod.Day;
    }
        set
        {
            switch (value)
            {
                case DateTimeTools.TimePeriod.Day:
                    for (int i=0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 0);
                    break;
                case DateTimeTools.TimePeriod.Week:
                    for (int i=0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 1);
                    break;
                case DateTimeTools.TimePeriod.Month:
                    for (int i=0; i < cmbPeriodType.Items.Count; i++) cmbPeriodType.Items[i].Selected = (i == 2);
                    break;
            }
        }
    }



    private bool ctlFilterBar1_OnFindClik(string sFindStr)
    {
        (Where.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtStart = DtStart ;
        (Where.ListLoadStatment as SideListWithContracts.SqlLoadStatment).DtFinish = DtEnd;
        (Where.ListLoadStatment as SideListWithContracts.SqlLoadStatment).Serch_Q_TypeSet = Q_TypeSet;
        Where.ListLoadStatment.Lexeme = ctlFilterBar1.Lexeme;
        MyDataBind();
        return true;
    }

    public void MyDataBind()
    {

        ObjectDS_PF ODS = new ObjectDS_PF(GetList);
        lvSides.DataSource = ODS.ImAsObjectDataSource;
        lvSides.DataBind();

    }

    public ListWhere Where
    {
        get
        {
            string key = "Where" + KeyPref;
            if (!CacheTools.IsSessionCacheObject(key))
            {
                ListWhere r = new ListWhere();
                r.ListLoadStatment = new SideListWithContracts.SqlLoadStatment();
                r.SortCondition.SortDirection = SortDirection.Ascending;
                r.SortCondition.SortField = "FullGID";
                CacheTools.SetSessionCacheObject(key, r);
            }
            return (ListWhere)CacheTools.GetSessionCacheObect(key);
        }
        set
        {

            string key = "Where" + KeyPref;
            CacheTools.SetSessionCacheObject(key, value);

        }

    }



    grdSideWitchShedule[] rs = null;
    protected grdSideWitchShedule[] GetList(int startRowIndex, int maximumRows, out int RowCount)
    {


        if (rs != null)
        {
            RowCount = rs.Length;
            return rs;
        }

            
        wsConstractions ws = (wsConstractions)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Constraction];                    
        SideListWithContracts.SideContractItemBox[] r = ws.GetSideListWithContracts((SideListWithContracts.SqlLoadStatment)Where.ListLoadStatment);

        RowCount = r.Length;
        rs = new grdSideWitchShedule[r.Length];
        int j = 0;
        foreach (SideListWithContracts.SideContractItemBox i in r)
        {
            rs[j] = new grdSideWitchShedule(i);
            j++;
        }
        RowCount = rs.Length;

        ////////заряжаем comparer функцией сортировки         
        Where.SortCondition.fnOrderBy = SortFunctions.fOrderBy;
        Array.Sort(rs, Where.SortCondition);
        return rs;
    }

    protected ListWhere GetWhere()
    {
        return Where;
    }


    #endregion


    /// <summary>
    /// Контракт отражаемый на расписании 
    /// </summary>
    protected  Contract Contract 
    {
        get 
        {
            if (string.IsNullOrEmpty(ContractId))
                                        return null;
 
            wsContract ws = (wsContract)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Contract]; 
            return ws.GetContract(ContractId);
        }
    }

    protected string ContractId 
    {
        get 
        {
            //if(string .IsNullOrEmpty ( Request["ContractID"] ))
            //    return Guid .NewGuid ().ToString ()+GlobalConstants .qPrefNEW_RECORD ;
            //else 
                return Request["ContractID"] ;
        }
    }

    /// <summary>
    /// Вернуть из контракта список периодов принадлежащих стороне 
    /// </summary>
    /// <param name="SideID"></param>
    /// <returns></returns>
    protected List <ContractSurfaceItem> GetContractSurfaceItem(string SideID)
    {
        List <ContractSurfaceItem> res= new List<ContractSurfaceItem> ();
        foreach (ContractSurfaceItem i in Contract.ContractSurfaceItemList)
        {
            if (i.SideID == SideID)
                        res.Add(i);
        }
        return res;
    }

    
    protected void btnContract_Click(object sender, EventArgs e)
    {
        CacheTools.ResetCache(sContractID);
        wsContract ws = (wsContract)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Contract]; 
        string id = GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString();
        Contract c = ws.GetContract (id);
        c.ID = sContractID;
        

        ContractSurfaceItem item = new ContractSurfaceItem()
        {
            ContractID = c.ID,            
            DtStart = DateTime.Now,
            DtFinish = DateTime.Now.AddDays(5),
            SideID = "a70e4be6-d8b0-4748-8263-c8bfeb57206f"
        };
        c.ContractStatus = new ContractStatus_Advice();
        c.ContractSurfaceItemList.Add(item);
        

        Contract NewC = ws.SaveContract(c);

        string sUrlKey = GlobalConstants.SiteMapItem_iSales_Contract ;
        string s = "PageProcessor.aspx?Page=" + sUrlKey + ".aspx?" + iSales_Page.qContractID + "=" + NewC.ID;
        Response.Redirect(s);


    }

    protected string GetHtmlRow(string SideID, SideShedule Shedule )
    {
        ContractSurfaceItemList l = null;

        if (null != Contract)
                l = Contract.ContractSurfaceItemList;
                    
        return SurfaceSheduleRowWriter.GetHtml(DetailsPeriod, Shedule, l);  
        

    }
}
